from flask import Flask, render_template, request,url_for,redirect
import randomsaying, os,random
from log import log_request

app = Flask(__name__)

@app.route('/')
def hello_world():
    """网站index页，点击进入欢迎页面"""
    title = 'study-sharing web'
    return render_template('index.html',
                           the_title=title, )

@app.route('/Welcome')
def welcome() -> 'html':
    """欢迎页，1.生成随机鼓励语并展示；2.选择登陆或注册功能"""
    saying = randomsaying.saying_making()  #引用random_saying函数，在欢迎页面上随机为用户生成一句鼓励语并展示出来。
    print(saying)
    return render_template('welcome.html',
                           saying=saying)

@app.route('/Signup')
def signup() -> 'html':
    """用户注册页，填写用户名和密码进行注册"""
    return render_template('register.html')

@app.route('/register', methods=['POST'])
def register():
    """用户注册提交"""
    username = request.form['username']  #username为用户表单中所提交的username（用户名）
    password = request.form['password']  #password为用户表单中所提交的password（密码）
    results = str(username)
    log_request(request,results)            #将所提交的用户名转化为str记录到日志中，为保护隐私password不计入
    with open(username+'.txt', 'w') as f:   #注册的用户会自动创建一个对应的以用户名为命名的TXT文件
        f.write(str(password))              #TXT文件中储存着用户在表单中提交的password
        return redirect(url_for('logging')) #完成创建后，点击button进入登录页面

@app.route('/logging')
def logging() -> 'html':
    """用户登录输入页"""
    return render_template('login.html')

@app.route('/login', methods=['POST'])
def login():
    """用户登录信息提交"""
    username = request.form['username']   #username为用户表单中所提交的username
    password = request.form['password']   #password为用户表单中所提交的password
    results = str(username)               #将所提交的用户名转化为str记录到日志中，为保护隐私password不计入
    log_request(request,results)
    if username+'.txt' not in os.listdir():             #根据是否存在用户所键入的账户来跳转到不同的页面
        return render_template('username-noexist.html')
    with open(username+'.txt', 'r') as f:
        f_password = f.read()
    if username+'.txt' in os.listdir() and password == f_password:
        return redirect(url_for('home', username=username))
    elif password != f_password:
        return render_template('wrongpassword.html')

@app.route('/Home')
def home() -> 'html':
    """网站首页"""
    title = 'This is my S&R website.'
    username = request.args.get('username') #接受login传过来的username参数，保持登录状态
    return render_template('home.html',
                           the_title=title,
                           username=username)

@app.route('/Recommend')
def recommmend() -> 'html':
    """Recommend分类页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('category-Recommend.html',
                           username=username)

@app.route('/Newest')
def Newest() -> 'html':
    """Newest分类页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('category-Newest.html',
                           username=username)

@app.route('/Highpraise')
def highpraise() -> 'html':
    """High-praise分类页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('category-High-praise.html',
                           username=username)

@app.route('/notebook-choice', methods=['GET', 'POST'])
def function_choose() -> 'html':
    """选择功能界面所执行的功能（记录或查看）"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('content-choice.html',
                           username=username,)

@app.route('/content-record', methods=['POST'])
def record() -> 'html':
    """输入需要记录的内容"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('content-record.html',
                           username=username,)

@app.route('/content-recording', methods=['POST','GET'])
def recording():
    """提交，将内容记录到记录本中"""
    title = '内容已被成功记录'
    content = request.form['content']
    remark = request.form['remark']
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    v = open(username+'-notebook.txt', 'a', encoding='utf-8')  #记录的过程中，有记录本的用户则计入到对应的记录本中，没有记录本的用户则为其创建一个记录本
    print(content+'!'+remark, file=v)
    v.close()
    E_results = str(content)           #将用户提交的记录内容计入日志中
    C_results = str(remark)        #将用户提交的备注计入日志中
    log_request(request,E_results)
    log_request(request, C_results)
    return render_template('content-record-successful.html',
                           the_title=title,
                           username=username,)

@app.route('/see-notebook', methods=['POST','GET'])
def seethenotebook():
    """查看记录本"""
    title = 'NOTE'
    username = request.args.get('username')     #接受上一个页面传过来的username参数，保持登录状态
    if username+'-notebook.txt' in os.listdir():   #判断用户是否有记录本，有则显示记录本内容，没有则提醒用户先去创建
        w = open(username + '-notebook.txt', 'r', encoding='utf-8')
        NOTE = w.read()
        the_content = NOTE.replace('!', ' ')
        print(the_content, end='')
        w.close()
        return render_template('see-notebook.html', username=username, the_title=title,the_content=the_content)
    elif username+'-notebook.txt' not in os.listdir():
        return render_template('notebook-noexist.html', username=username)


@app.route('/Recommend-passage')
def Recommend_passage():
    """推荐(Recommend)文章页"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('passage-Recommend.html',
                           username=username)


@app.route('/Newest-passage')
def Newest_passage() -> 'html':
    """最新(Newest)文章页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('passage-Newest.html',
                           username=username)

@app.route('/Highpraise-passage')
def highpraise_passsage() -> 'html':
    """高赞(highpraise)文章页面"""
    username = request.args.get('username')    #接受上一个页面传过来的username参数，保持登录状态
    return render_template('passage-High-praise.html',
                           username=username)

@app.route('/Log', methods=['GET'])
def view_the_log() -> 'html':
    """日志(Log)浏览页"""
    username = request.args.get('username')    #接受上一个页面传过来的username参数，保持登录状态
    with open('S&R.log') as log:
        contents = log.read()
        return render_template('viewlog.html',
                               contents=contents,
                               username=username)

if __name__ == '__main__':
    app.run()
